package com.apes.fico.finance.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fico.finance.model.costcollect.StaffSalaries;
import com.apes.fico.finance.model.costcollect.StoreTasks;
import com.apes.fico.finance.model.costcollect.TypeCost;
import com.apes.fico.finance.model.costcollect.WaterElectricityRent;
import com.apes.fico.finance.respository.StaffSalariesDao;
import com.apes.fico.finance.respository.StaffSalariesRepository;
import com.apes.fico.finance.respository.StoreTasksRepository;
import com.apes.fico.finance.respository.TypeCostRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.outbox.OutboxPayloadWrapper;
import com.apes.framework.plugin.outbox.OutboxSubscriberService;
import com.apes.framework.plugin.outbox.annotation.OutboxSubscriber;
import com.apes.framework.util.Arith;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.MapUtil;
import com.apes.hr.base.model.WorkPostGroup;
import com.apes.hr.base.repository.WorkPostGroupRepository;
import com.apes.hr.base.repository.WorkPostRepository;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author cyy
 * @Date 2022/12/13 15:47
 **/
@Service("staffSalariesService")
public class StaffSalariesService extends DomainService {

    @Autowired
    private StaffSalariesRepository staffSalariesRepository;
    @Autowired
    private DeptRepository deptRepository;
    @Autowired
    private PartyRoleRepository partyRoleRepository;
    @Autowired
    private WorkPostRepository workPostRepository;
    @Autowired
    private WorkPostGroupRepository workPostGroupRepository;
    @Autowired
    private StoreTasksRepository storeTasksRepository;

    public final static String RTGZ = "人员工资";

    /**
     * 批量创建
     *
     * @param request
     * @return
     */
    public Map save(SimpleRequest request) {
        List<StaffSalaries> staffSalariesList = JSON.parseArray(request.getJO().getString("staffSalaries"), StaffSalaries.class);
        staffSalariesList.forEach(staffSalarie -> {
            if ("bluntProvision".equals(staffSalarie.getType()) || "bluntActually".equals(staffSalarie.getType()))
                throw new RuntimeException("当前选择类型不允许保存，请确认！");
            StaffSalaries staffSalaries = staffSalariesRepository.findByDeptCompanyPerson(staffSalarie.getDept().getId(), staffSalarie.getCompany().getId(),
                    staffSalarie.getPerson().getId(), DateUtil.format(staffSalarie.getYearMonth(), DateUtil.SHOW_MONTH_FORMAT), staffSalarie.getType());
            if (!StringUtils.isEmpty(staffSalaries)) {
                if ((staffSalaries.getXsTc() == 0 && staffSalaries.getSgTc() == 0 && staffSalaries.getSubsidyAmt() == 0 ||
                        staffSalaries.getNetSalaryAmt() != 0)) throw new RuntimeException("本月已创建,无法重复创建");
            }

            if ("provision".equals(staffSalarie.getType()) && !StringUtils.isEmpty(staffSalaries)) {
                staffSalarie.setXsTc(staffSalaries.getXsTc());
                staffSalarie.setSgTc(staffSalaries.getSgTc());
                staffSalarie.setSubsidyAmt(staffSalaries.getSubsidyAmt());
                staffSalarie.setTcTotal(staffSalarie.getXsTc() + staffSalarie.getSgTc());
                staffSalarie.setWagesPayableAmt(staffSalarie.getWagesPayableAmt() + staffSalarie.getTcTotal() + staffSalarie.getSubsidyAmt());
                staffSalarie.setNetSalaryAmt(staffSalarie.getNetSalaryAmt() + staffSalarie.getTcTotal() + staffSalarie.getSubsidyAmt());
                staffSalariesRepository.delete(staffSalaries.getId());
            }
            staffSalarie.setCreator(request.getPersonId());
            staffSalarie.setCreateDate(new Date());
            staffSalarie.setPerson(SpringManager.getBean(PartyRoleRepository.class).findAll(JpaDsl.toCriteriaByEq("party.name", staffSalarie.getPerson().getName())).get(0));
        });
        List<StaffSalaries> salaries = staffSalariesRepository.saveAll(staffSalariesList);
        accumulation(salaries);
        return MapUtil.mapper("staffSalaries", salaries);
    }

    public void accumulation(List<StaffSalaries> staffSalaries) {
        Random rand = new Random();
        String aggregateId = String.valueOf(rand.nextInt(90000) + 10000);  // 生成5位随机码，串行消费
        staffSalaries.forEach(staffSalaries1 -> {
            JSONObject payload = new JSONObject();
            payload.put("id", staffSalaries1.getId());
            SpringManager.getBean(OutboxSubscriberService.class).commonSendRequest("fin.staffSalaries.costAccumulation", aggregateId, payload);
        });
    }

    @OutboxSubscriber(id="fin.staffSalaries.costAccumulation", name="计算门店经营成本（人员工资）")
    private void costAccumulation(OutboxPayloadWrapper outboxPayloadWrapper) {
        JSONObject payload = JSONObject.parseObject(outboxPayloadWrapper.getPayload());
        StaffSalaries staffSalaries1 = staffSalariesRepository.findOne(payload.getString("id"));
        if (staffSalaries1 == null) return;

        WorkPostGroup one = staffSalaries1.getPostGroup();
        // 统计需要回写经营成本
        if (staffSalaries1.getSgTc() != 0 && !("provision".equals(staffSalaries1.getType()) || "bluntProvision".equals(staffSalaries1.getType()))) {//施工提成
            extracted(staffSalaries1, staffSalaries1.getSgTc(), "3");
        }
        if (staffSalaries1.getXsTc() != 0 && !("provision".equals(staffSalaries1.getType()) || "bluntProvision".equals(staffSalaries1.getType()))) {//销售提成
            extracted(staffSalaries1, staffSalaries1.getXsTc(), "2");
        }

        if (staffSalaries1.getRepayment() != 0) {//还借款
            extracted(staffSalaries1, staffSalaries1.getRepayment(), "00000003");
        }

        if (staffSalaries1.getAccount() != 0) {//系统挂账
            extracted(staffSalaries1, staffSalaries1.getAccount(), "00000002");
        }

        if (staffSalaries1.getWithhold() != 0) {//代扣工会费
            extracted(staffSalaries1, staffSalaries1.getWithhold(), "00000004");
        }
        if (staffSalaries1.getEarningsTax() != 0) {//个人所得税
            extracted(staffSalaries1, staffSalaries1.getEarningsTax(), "00000001");
        }
        if (staffSalaries1.getElectricity() != 0) {//个人水电
            extracted(staffSalaries1, staffSalaries1.getElectricity(), "00000005");
        }
        if (staffSalaries1.getNetSalaryAmt() != 0) {//实发工资
            extracted(staffSalaries1, staffSalaries1.getNetSalaryAmt(), "22");
        }
        if (staffSalaries1.getSocialSecurityCompanyAmt() != 0) {//社保(公司)
            extracted(staffSalaries1, staffSalaries1.getSocialSecurityCompanyAmt(), "7");
        }
        if (staffSalaries1.getAccumulationFundCompanyAmt() != 0) {//公积金(公司)
            extracted(staffSalaries1, staffSalaries1.getAccumulationFundCompanyAmt(), "8");
        }
        if (staffSalaries1.getSocialSecurityPersonAmt() != 0) {//社保(个人)
            extracted(staffSalaries1, staffSalaries1.getSocialSecurityPersonAmt(), "20");
        }
        if (staffSalaries1.getAccumulationFundPersonAmt() != 0) {//公积金(个人)
            extracted(staffSalaries1, staffSalaries1.getAccumulationFundPersonAmt(), "21");
        }
        if ("002145".equals(one.getJobType().getId())) {//是否是管理组
            if (staffSalaries1.getBaseAmt() != 0) {//基本工资
                extracted(staffSalaries1, staffSalaries1.getBaseAmt(), "1");
            }
            if (staffSalaries1.getSubsidyAmt() != 0 && !("provision".equals(staffSalaries1.getType()) || "bluntProvision".equals(staffSalaries1.getType()))) {//支援补贴
                extracted(staffSalaries1, staffSalaries1.getSubsidyAmt(), "5");
            }
            if (staffSalaries1.getRewardPunishmentAmt() != 0) {//奖惩
                extracted(staffSalaries1, staffSalaries1.getRewardPunishmentAmt(), "6");
            }
        } else {
            if (staffSalaries1.getBaseAmt() != 0) {//基本工资
                extracted(staffSalaries1, staffSalaries1.getBaseAmt(), "4");
            }
            if (staffSalaries1.getSubsidyAmt() != 0 && !("provision".equals(staffSalaries1.getType()) || "bluntProvision".equals(staffSalaries1.getType()))) {//支援补贴
                extracted(staffSalaries1, staffSalaries1.getSubsidyAmt(), "19");
            }
            if (staffSalaries1.getRewardPunishmentAmt() != 0) {//奖惩
                extracted(staffSalaries1, staffSalaries1.getRewardPunishmentAmt(), "18");
            }

        }
    }

    private void extracted(StaffSalaries staffSalaries, double amt, String typeCost) {
        TypeCost typeCostOne = SpringManager.getBean(TypeCostRepository.class).findOne(typeCost);
        this.invoke("finance.operatingCosts.costAccumulation", MapUtil.mapper("amt", amt, "state", staffSalaries.getType(),
                "yearMonth", DateUtil.format(staffSalaries.getYearMonth(), "yyyy-MM-dd"), "dept", staffSalaries.getDept().getId(),
                "typeCost", typeCostOne.getId(), "costType", typeCostOne.getInComeCategory().getId(), "company", staffSalaries.getDeptCompany().getId(),
                "sourceReceipt", "人员工资", "sourceId", staffSalaries.getId(), "person", staffSalaries.getPerson(), "declareCompany", staffSalaries.getCompany()));
    }

    /**
     * 冲红
     *
     * @param request
     * @return
     */
    public Map reversal(SimpleRequest request) {
        List<StaffSalaries> staffSalariesList = JSON.parseArray(request.getJO().getString("staffSalaries"), StaffSalaries.class);
        List<StaffSalaries> salariesList = new ArrayList<>();
        staffSalariesList.forEach(v -> {
            if (v.getSelected() == false) return; //未勾选的数据不变更
            if (!v.isValid())
                throw new RuntimeException(v.getDept().getId() + "[" + v.getDept().getName() + "], 已冲红，请确认！");
            if ("bluntProvision".equals(v.getType()) || "bluntActually".equals(v.getType()))
                throw new RuntimeException("当前选择类型不允许冲红，请确认！");
            StaffSalaries staffSalaries = new StaffSalaries();
            v.setValid(false);
            try {
                staffSalaries.setCreator(request.getPersonId());
                staffSalaries.setCreateDate(new Date());
                staffSalaries.setDept(v.getDept());//部门
                staffSalaries.setCompany(v.getCompany());//申报公司
                staffSalaries.setDeptCompany(v.getDeptCompany());//所属公司
                staffSalaries.setYearMonth(v.getYearMonth());//年月
                staffSalaries.setPostGroup(v.getPostGroup());//岗位
                staffSalaries.setPerson(v.getPerson());//人员
                staffSalaries.setSummary(v.getSummary());//备注
                staffSalaries.setType("provision".equals(v.getType()) ? "bluntProvision" : "bluntActually");
                staffSalaries.setBaseAmt(v.getBaseAmt() * -1);//基本工资
                staffSalaries.setSgTc(v.getSgTc() * -1);//施工提成
                staffSalaries.setXsTc(v.getXsTc() * -1);//销售提成
                staffSalaries.setSubsidyAmt(v.getSubsidyAmt() * -1);//支援补贴
                staffSalaries.setRewardPunishmentAmt(v.getRewardPunishmentAmt() * -1);//奖惩
                staffSalaries.setAccount(v.getAccount() * -1);//系统挂账
                staffSalaries.setRepayment(v.getRepayment() * -1);//还借款
                staffSalaries.setWithhold(v.getWithhold() * -1);//代扣工会费
                staffSalaries.setElectricity(v.getElectricity() * -1);//个人水电
                staffSalaries.setEarningsTax(v.getEarningsTax() * -1);//个人所得税
                staffSalaries.setSocialSecurityPersonAmt(v.getSocialSecurityPersonAmt() * -1);//社保(个人)
                staffSalaries.setSocialSecurityCompanyAmt(v.getSocialSecurityCompanyAmt() * -1);//社保(公司)
                staffSalaries.setAccumulationFundCompanyAmt(v.getAccumulationFundCompanyAmt() * -1);//公积金(公司)
                staffSalaries.setAccumulationFundPersonAmt(v.getAccumulationFundPersonAmt() * -1);//公积金(个人)
                staffSalaries.setTcTotal(v.getTcTotal() * -1);//总提成
                staffSalaries.setWagesPayableAmt(v.getWagesPayableAmt() * -1);//应发工资
                staffSalaries.setNetSalaryAmt(v.getNetSalaryAmt() * -1);//实发工资
            } catch (ParseException e) {
                e.printStackTrace();
            }
            saveAndFlush(v);
            salariesList.add(saveAndFlush(staffSalaries));
        });
        accumulation(salariesList);
        return MapUtil.mapper("staffSalaries", salariesList, "test", true);
    }

    private StaffSalaries saveAndFlush(StaffSalaries salaries) {
        return staffSalariesRepository.saveAndFlush(salaries);
    }

    /**
     * 操作页面查询
     *
     * @param request
     * @return
     */
    public List findOneToList(SimpleRequest request) {
        JSONObject object = request.getJO();
        if (StringUtils.isEmpty(object.get("type"))) throw new RuntimeException("类型必选，请选择！");
        JSONArray jsonArray = SpringManager.getBean(StaffSalariesDao.class).queryAllTransactionFlow(object, request.getPostId());
        List result = jsonArray.stream().map(item -> {
            JSONObject jsonObject = (JSONObject) item;
            Dept dept = SpringManager.getBean(DeptRepository.class).findOne(jsonObject.getString("DEPT_ID"));
            return MapUtil.mapper("dept", dept,
                    "deptCompany", dept.getCompany(),
                    "yearMonth", jsonObject.getString("YEAR_MONTH"), "type", jsonObject.getString("TYPE"),
                    "person", jsonObject.getString("PERSON_ID") != null ? SpringManager.getBean(PartyRoleRepository.class).findOne(jsonObject.getString("PERSON_ID")) : null,
                    "postGroup", jsonObject.getString("POST_GROUP_ID") != null ? SpringManager.getBean(WorkPostGroupRepository.class).findOne(jsonObject.getString("POST_GROUP_ID")) : null,
                    "baseAmt", jsonObject.getString("BASE_AMT"),
                    "tcTotal", jsonObject.getString("TC_TOTAL"),
                    "sgtc", jsonObject.getString("SGTC"),
                    "xstc", jsonObject.getString("XSTC"),
                    "subsidyAmt", jsonObject.getString("SUBSIDY_AMT"),
                    "account", jsonObject.getString("ACCOUNT"),
                    "repayment", jsonObject.getString("REPAYMENT"),
                    "withhold", jsonObject.getString("WITHHOLD"),
                    "electricity", jsonObject.getString("ELECTRICITY"),
                    "earningsTax", jsonObject.getString("EARNINGS_TAX"),
                    "rewardPunishmentAmt", jsonObject.getString("REWAR_PUNISHMENT_AMT"),
                    "socialSecurityCompanyAmt", jsonObject.getString("SOCIAL_SECURITY_COMPANY_AMT"),
                    "socialSecurityPersonAmt", jsonObject.getString("SOCIAL_SECURITY_PERSON_AMT"),
                    "accumulationFundCompanyAmt", jsonObject.getString("ACCUMULATION_FUND_COMPANY_AMT"),
                    "accumulationFundPersonAmt", jsonObject.getString("ACCUMULATION_FUND_PERSON_AMT"),
                    "wagesPayableAmt", jsonObject.getString("WAGES_PAYABLE_AMT"),
                    "netSalaryAmt", jsonObject.getString("NET_SALARY_AMT"),
                    "company", SpringManager.getBean(PartyRoleRepository.class).findOne(jsonObject.getString("COMPANY_ID")),
                    "valid", jsonObject.getString("VALID"),
                    "id", jsonObject.getString("ID"),
                    "summary", jsonObject.getString("SUMMARY"));
        }).collect(Collectors.toList());
        return result;
    }

    // 导入
    public Map importLogic(SimpleRequest request) {
        JSONObject getJO = request.getJO();
        // 数据匹配
        // 数据校验 判断前端明细是否有数据
        JSONObject modelJson = getJO.getJSONObject("model");
        // 数据匹配
        List maps = builderResultList(getJO.getJSONObject("importData"));

        return MapUtil.mapper("items", maps, "msg", "");
    }

    private List builderResultList(JSONObject importData) {
        List resultList = new ArrayList<>();
        importData.forEach((sheetName, excelItems) -> {
            JSONArray importDataValueArray = (JSONArray) excelItems;
            importDataValueArray.forEach(excelItem -> {
                //通过状态判断是否是有序号
                if ("序号".equals(((JSONArray) excelItem).get(0).toString()))
                    throw new RuntimeException("导入不需要序号，请除去序号，重新进行导入！");
                if ("计提".equals(((JSONArray) excelItem).get(3).toString()) || "实际发生".equals(((JSONArray) excelItem).get(3).toString())) {

                    Dept byName = SpringManager.getBean(DeptRepository.class).findOne(((JSONArray) excelItem).get(0).toString().trim());
                    if (Objects.isNull(byName))
                        throw new RuntimeException("请检查数据部门:" + ((JSONArray) excelItem).get(0).toString());
                    if (StringUtils.isEmpty(((JSONArray) excelItem).get(7)) || StringUtils.isEmpty(((JSONArray) excelItem).get(8)) || StringUtils.isEmpty(((JSONArray) excelItem).get(9)))
                        throw new RuntimeException("销售提成，施工提成，支援补贴不允许为空，请检查！");
                    if ("计提".equals(((JSONArray) excelItem).get(3).toString()) && (Double.valueOf(((JSONArray) excelItem).get(7).toString()) > 0
                            || Double.valueOf(((JSONArray) excelItem).get(8).toString()) > 0 || Double.valueOf(((JSONArray) excelItem).get(9).toString()) > 0))
                        throw new RuntimeException("'计提'时无法导入销售提成、施工提成、支援补贴");

                    Map<String, Object> map = staffSalariesRepository.findByName(((JSONArray) excelItem).get(4).toString());

                    if (Objects.isNull(((JSONArray) excelItem).get(1).toString()))
                        throw new RuntimeException("公司不允许为空！！");
                    PartyRole company = SpringManager.getBean(PartyRoleRepository.class).findOne(((JSONArray) excelItem).get(1).toString());
                    if (Objects.isNull(company))
                        throw new RuntimeException("请检查数据:" + ((JSONArray) excelItem).get(1).toString());

                    String type;//类型
                    if ("计提".equals(((JSONArray) excelItem).get(3).toString())) {
                        type = "provision";
                    } else if ("实际发生".equals((((JSONArray) excelItem).get(3).toString()))) {
                        type = "actually";
                    } else if ("冲计提".equals((((JSONArray) excelItem).get(3).toString()))) {
                        type = "bluntAccrual";
                    } else if ("冲实际发生".equals((((JSONArray) excelItem).get(3).toString()))) {
                        type = "bluntActually";
                    } else {
                        type = "";
                    }

                    //总提成 = 销售提成+施工提成
                    double tcTotal = isEmpty(((JSONArray) excelItem).get(7)) + isEmpty(((JSONArray) excelItem).get(8));

                    //应发工资=基本工资+总提成+支援补贴+奖惩
                    double wagesPayableAmt = isEmpty(((JSONArray) excelItem).get(6)) + tcTotal + isEmpty(((JSONArray) excelItem).get(9)) + isEmpty(((JSONArray) excelItem).get(10));

                    //实发工资=应发工资-个人社保-个人所得税-系统挂账-还借款-代扣工会费-个人水电费
                    double netSalaryAmt = wagesPayableAmt - isEmpty(((JSONArray) excelItem).get(17)) - isEmpty(((JSONArray) excelItem).get(15))
                            - isEmpty(((JSONArray) excelItem).get(11)) - isEmpty(((JSONArray) excelItem).get(12)) - isEmpty(((JSONArray) excelItem).get(13))
                            - isEmpty(((JSONArray) excelItem).get(14));

                    resultList.add(MapUtil.mapper("dept", byName,
                            "deptCompany", byName.getCompany(),
                            "company", company,
                            "yearMonth", ((JSONArray) excelItem).get(2).toString(),
                            "type", type,
                            "person", SpringManager.getBean(PartyRoleRepository.class).findAll(JpaDsl.toCriteriaByEq("party.name", ((JSONArray) excelItem).get(4).toString())).get(0),
                            "postGroup", SpringManager.getBean(WorkPostGroupRepository.class).findOne((String) map.get("post_group_id")),
                            "baseAmt", isEmpty(((JSONArray) excelItem).get(6)),//基本工资
                            "sgtc", isEmpty(((JSONArray) excelItem).get(7)),//施工提成
                            "xstc", isEmpty(((JSONArray) excelItem).get(8)),//销售提成
                            "subsidyAmt", isEmpty(((JSONArray) excelItem).get(9)),//支援补贴
                            "rewardPunishmentAmt", isEmpty(((JSONArray) excelItem).get(10)),//奖惩
                            "account", isEmpty(((JSONArray) excelItem).get(11)),//系统挂账
                            "repayment", isEmpty(((JSONArray) excelItem).get(12)),//还借款
                            "withhold", isEmpty(((JSONArray) excelItem).get(13)),//代扣工会费
                            "electricity", isEmpty(((JSONArray) excelItem).get(14)),//个人水电费
                            "earningsTax", isEmpty(((JSONArray) excelItem).get(15)),//个人所得税
                            "socialSecurityCompanyAmt", isEmpty(((JSONArray) excelItem).get(16)),//社保(公司)
                            "socialSecurityPersonAmt", isEmpty(((JSONArray) excelItem).get(17)),//社保(个人)
                            "accumulationFundCompanyAmt", isEmpty(((JSONArray) excelItem).get(18)),//公积金(公司)
                            "accumulationFundPersonAmt", isEmpty(((JSONArray) excelItem).get(19)),//公积金(个人)
                            "summary", ((JSONArray) excelItem).size() > 20 && ((JSONArray) excelItem).get(20) != null ? ((JSONArray) excelItem).get(20).toString() : null,//摘要
                            "tcTotal", tcTotal,//总提成
                            "wagesPayableAmt", wagesPayableAmt,//应发工资
                            "netSalaryAmt", netSalaryAmt//实发工资
                    ));
                }
            });
        });
        return resultList;
    }


    public double isEmpty(Object sum) {
        return StringUtils.isEmpty(sum) == true ? 0 : Double.parseDouble(sum.toString());
    }

    /**
     * 保存方法
     *
     * @param transactionFlow
     * @return
     */
    public StaffSalaries saveTransactionFlow(StaffSalaries transactionFlow) {
        StaffSalaries flow = staffSalariesRepository.saveAndFlush(transactionFlow);
        return flow;
    }

    //定时任务按月统计所有提成
    private void saveTc(SimpleRequest request) {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, -1);
        Date lastMonth = c.getTime();
        String months = DateUtil.format(lastMonth, "MM");
        String years = DateUtil.format(lastMonth, "YYYY");
        List<Map<String, Object>> TCJE = staffSalariesRepository.TCJE(months, years);
        TCJE.forEach(map -> {
            StaffSalaries staffSalaries = new StaffSalaries();
            Dept dept = deptRepository.findOne(map.get("deptId").toString());
            if (ObjectUtils.isEmpty(dept)) {
                return;
            }
            staffSalaries.setDept(dept);
            try {
                staffSalaries.setYearMonth(DateUtil.format(lastMonth, DateUtil.SHOW_DATE_FORMAT));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            staffSalaries.setType("provision");
            if (map.get("person") != null) {
                PartyRole person = partyRoleRepository.findOne(map.get("person").toString());
                staffSalaries.setPerson(person);
                String workPostGroupId = workPostRepository.findByPerson(person.getName());
                if (workPostGroupId != null)
                    staffSalaries.setPostGroup(workPostGroupRepository.findOne(workPostGroupId));
            }
            StoreTasks storeTasks = storeTasksRepository.findByYearMonthAndDept(months, years, dept.getId());
            double taskRate = 1;
            if (storeTasks != null)
                taskRate = Arith.round(storeTasks.getBusinessAmt() / storeTasks.getBusinessTasksAmt(), 2);
            double xstc = Double.parseDouble(map.get("XSTC").toString());
            if (taskRate >= 1) {
                staffSalaries.setXsTc(xstc);
            } else if (taskRate < 1 && taskRate > 0.5) {
                staffSalaries.setXsTc(Arith.round(xstc * taskRate, 2));
            } else {
                staffSalaries.setXsTc(xstc * 0.5);
            }
            staffSalaries.setSgTc(Double.parseDouble(map.get("SGTC").toString()));
            staffSalaries.setSubsidyAmt(Double.parseDouble(map.get("BTJE").toString()));
            staffSalariesRepository.saveAndFlush(staffSalaries);
            costAccumulation(staffSalaries);
        });
    }

    public void costAccumulation(StaffSalaries staffSalaries) {
        if (staffSalaries.getSgTc() != 0) {
            this.invoke("finance.operatingCosts.costAccumulation", MapUtil.mapper("amt", staffSalaries.getSgTc(), "state", "provision",
                    "yearMonth", DateUtil.format(staffSalaries.getYearMonth(), "yyyy-MM-dd"), "dept", staffSalaries.getDept().getId(),
                    "company", staffSalaries.getDept().getCompany().getId(), "typeCost", "3", "costType", "002107",
                    "sourceReceipt", "人员工资", "sourceId", staffSalaries.getId(), "person", staffSalaries.getPerson(), "declareCompany", staffSalaries.getCompany()));
        }
        if (staffSalaries.getXsTc() != 0) {
            this.invoke("finance.operatingCosts.costAccumulation", MapUtil.mapper("amt", staffSalaries.getXsTc(), "state", "provision",
                    "yearMonth", DateUtil.format(staffSalaries.getYearMonth(), "yyyy-MM-dd"), "dept", staffSalaries.getDept().getId(),
                    "company", staffSalaries.getDept().getCompany().getId(), "typeCost", "2", "costType", "002105",
                    "sourceReceipt", "人员工资", "sourceId", staffSalaries.getId(), "person", staffSalaries.getPerson(), "declareCompany", staffSalaries.getCompany()));
        }
        if (staffSalaries.getSubsidyAmt() != 0) {
            this.invoke("finance.operatingCosts.costAccumulation", MapUtil.mapper("amt", staffSalaries.getSubsidyAmt(), "state", "provision",
                    "yearMonth", DateUtil.format(staffSalaries.getYearMonth(), "yyyy-MM-dd"), "dept", staffSalaries.getDept().getId(),
                    "company", staffSalaries.getDept().getCompany().getId(), "typeCost", "5", "costType", "002107",
                    "sourceReceipt", "人员工资", "sourceId", staffSalaries.getId(), "person", staffSalaries.getPerson(), "declareCompany", staffSalaries.getCompany()));
        }
    }
}
